package com.nefu.softlab.xjwc.service.impl;

import com.nefu.softlab.xjwc.common.Constant;
import com.nefu.softlab.xjwc.mapper.*;
import com.nefu.softlab.xjwc.model.Activity;
import com.nefu.softlab.xjwc.model.Project;
import com.nefu.softlab.xjwc.model.Score;
import com.nefu.softlab.xjwc.service.ProjectService;
import com.nefu.softlab.xjwc.utils.FileUtil;
import com.nefu.softlab.xjwc.utils.XJWCException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : Ar1es
 * @date : 2020/2/8
 * @since : Java 8
 */
@SuppressWarnings("AlibabaTransactionMustHaveRollback")
@Service
public class ProjectServiceImpl implements ProjectService {

    private final ProjectMapper projectMapper;
    private final RedisMapper redisMapper;
    private final ActivityMapper activityMapper;
    private final DocumentMapper documentMapper;
    private final ScoreMapper scoreMapper;

    @Autowired
    public ProjectServiceImpl(ProjectMapper projectMapper, RedisMapper redisMapper, ActivityMapper activityMapper, DocumentMapper documentMapper, ScoreMapper scoreMapper) {
        this.projectMapper = projectMapper;
        this.redisMapper = redisMapper;
        this.activityMapper = activityMapper;
        this.documentMapper = documentMapper;
        this.scoreMapper = scoreMapper;
    }

    @Transactional
    @Override
    public int insertProject(Project project) throws XJWCException {
        if (redisMapper.hasKey(Constant.PROJECT_LIST + project.getActivityId())) {
            redisMapper.del(Constant.PROJECT_LIST + project.getActivityId());
        }

        List<String> pros = projectMapper.selectProjectNameByName(project.getName());
        if (pros.size() == 1) {
            throw new XJWCException("项目名称已存在,请检查");
        }

        int flag = projectMapper.insertProject(project);

        Activity activity = activityMapper.selectActivityByProjectId(project.getProjectId()).get(0);

        String projectDir = activity.getActivityId() + "-" + activity.getName()
                + "/" + project.getProjectId() + "-" + project.getName();

        System.out.print("ProjectServiceImpl.insertProject() : mkdir --> projectDir : " + projectDir);

        FileUtil.mkdir(projectDir);

        if (0 < flag) {
            return project.getProjectId();
        } else {
            throw new XJWCException("新建项目失败，请重新尝试!");
        }
    }

    /**
     * 前端不传文件会调传文件的接口
     * @param project
     * @return
     * @throws XJWCException
     */
    @Transactional
    @Override
    public int updateProject(Project project) throws XJWCException {
        if (redisMapper.hasKey(Constant.PROJECT_LIST + project.getActivityId())) {
            redisMapper.del(Constant.PROJECT_LIST + project.getActivityId());
        }

        int flag = projectMapper.updateProject(project);

        if (0 < flag) {
            return flag;
        } else {
            throw new XJWCException("更新项目失败，请重新尝试!");
        }
    }

    @Transactional
    @Override
    public int deleteProject(Project project) throws XJWCException {
        if (redisMapper.hasKey(Constant.PROJECT_LIST + project.getActivityId())) {
            redisMapper.del(Constant.PROJECT_LIST + project.getActivityId());
        }

        Activity activity = activityMapper.selectActivityByProjectId(project.getProjectId()).get(0);
        project = projectMapper.selectAllProject1(project).get(0);

        String projectDir = Constant.UPLOAD_PATH_PREFIX
                + activity.getActivityId() + "-" + activity.getName()
                + "/" + project.getProjectId() + "-" + project.getName() + "/";

        System.out.println("delete project's dirPath : " + projectDir);

        // 删除文件表的项目信息。
        documentMapper.deleteDocument(project.getProjectId());

        // 删除项目文件夹
        FileUtil.delAllFile(new File(projectDir));

        int flag = projectMapper.deleteProject(project);
        if (0 < flag) {
            return flag;
        } else {
            throw new XJWCException("删除项目失败，请重新尝试!");
        }
    }

    @Override
    public int deleteProject1(Project project) throws XJWCException {
        if (redisMapper.hasKey(Constant.PROJECT_LIST + project.getActivityId())) {
            redisMapper.del(Constant.PROJECT_LIST + project.getActivityId());
        }

        Activity activity = activityMapper.selectActivityByProjectId(project.getProjectId()).get(0);
        project = projectMapper.selectAllProject2(project).get(0);

        String projectDir = Constant.UPLOAD_PATH_PREFIX
                + activity.getActivityId() + "-" + activity.getName()
                + "/" + project.getProjectId() + "-" + project.getName() + "/";

        System.out.println("delete project's dirPath : " + projectDir);
        scoreMapper.deleteScoreByProjectId(project.getProjectId());

        // 删除项目文件夹
        FileUtil.delAllFile(new File(projectDir));


        int flag = projectMapper.deleteProject(project);
        if (0 < flag) {
            return flag;
        } else {
            throw new XJWCException("删除项目失败，请重新尝试!");
        }
    }

    @Override
    public Object selectAllProject(Project project) throws XJWCException {
        if (redisMapper.hasKey(Constant.PROJECT_LIST + project.getActivityId())) {
            return redisMapper.get(Constant.PROJECT_LIST + project.getActivityId());
        }
        List<Map<String, Object>> al = new ArrayList<>();
        List<Project> list = projectMapper.selectAllProject(project);

        if (null != list) {
            for (Project p : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("projectId", p.getProjectId());
                map.put("activityId", p.getActivityId());
                map.put("name", p.getName());
                map.put("info", p.getInfo());
                map.put("leader", p.getLeader());
                map.put("unit", p.getUnit());
                map.put("score", p.getScore());
                map.put("docUrl", p.getDocUrl());
                al.add(map);
            }
        } else {
            throw new XJWCException("查询项目出现异常，请重新尝试!");
        }
        redisMapper.set(Constant.PROJECT_LIST + project.getActivityId(), al);
        return al;
    }

    @Override
    public List<Map<String, Object>> selectProjectByKeyword(String keyword) throws XJWCException {
        List<Map<String, Object>> al = new ArrayList<>();
        List<Project> list = projectMapper.selectProjectByKeyword(keyword);
        if (null != list && 0 != list.size()) {
            for (Project p : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("score", p.getScore());
                map.put("unit", p.getUnit());
                map.put("activityId", p.getActivityId());
                map.put("name", p.getName());
                map.put("info", p.getInfo());
                map.put("leader", p.getLeader());
                map.put("projectId", p.getProjectId());
                al.add(map);
            }
        } else {
            throw new XJWCException("查询项目出现异常，请重新尝试!");
        }
        return al;
    }

    @Override
    public List<Map<String, Object>> selectSortProject() throws XJWCException {
        List<Map<String, Object>> al = new ArrayList<>();
        List<Project> list = projectMapper.selectSortProject();
        if (null != list && 0 != list.size()) {
            for (Project p : list) {
                Map<String, Object> map = new HashMap<>();
                map.put("projectId", p.getProjectId());
                map.put("score", p.getScore());
                map.put("unit", p.getUnit());
                map.put("name", p.getName());
                map.put("info", p.getInfo());
                map.put("leader", p.getLeader());
                map.put("activityId", p.getActivityId());
                al.add(map);
            }
        } else {
            throw new XJWCException("查询项目出现异常，请重新尝试!");
        }
        return al;
    }

    @Override
    public Object selectProIdByActivityId(Integer activityId, String name) throws XJWCException {
        Object rtv;
        if (null != (rtv = projectMapper.selectProIdByActivityId(activityId, name))) {
            return rtv;
        } else {
            throw new XJWCException("没有符合条件的项目!");
        }
    }

    @Override
    public Map<String, Object> selectProjectDetail(Integer projectId) throws XJWCException {
        Project project = new Project();
        project.setProjectId(projectId);

        List<Project> pros = projectMapper.selectAllProject1(project);
        List<Activity> acts = activityMapper.selectActivityByProjectId(projectId);

        if (acts.size() != 1 || pros.size() != 1 ) {
            throw new XJWCException("查询项目出现异常，请重新尝试!");
        }
        Map<String, Object> map = new HashMap<>();
        Project pro1 = pros.get(0);
        Activity act1 = acts.get(0);

        map.put("projectId", pro1.getProjectId());
        map.put("activityId", pro1.getActivityId());
        map.put("unit", pro1.getUnit());
        map.put("leader", pro1.getLeader());
        map.put("name", pro1.getName());
        map.put("info", pro1.getInfo());
        map.put("score", pro1.getScore());

        if (redisMapper.hasKey(Constant.TAG_ACTIVITY + act1.getActivityId().toString())) {
            map.put("tag", redisMapper.get(Constant.TAG_ACTIVITY + act1.getActivityId().toString()));
        } else {
            map.put("tag", "");
        }
        if (redisMapper.hasKey(act1.getActivityId().toString())) {
            map.put("list", redisMapper.get(act1.getActivityId().toString()));
        } else {
            map.put("list", "");
        }

        return map;

    }


    @Override
    public List<Map<String, Object>> getProjectByUserAndActivity(String userId, Integer activityId) throws XJWCException {
        List<Project> list = projectMapper.selectAllProjectByActivityId(activityId);
        if (list == null) {
            throw new XJWCException("查询项目出现异常，请重新尝试!");
        }

        List<Map<String, Object>> lm = new ArrayList<>();

        list.parallelStream().forEach(p -> {
            Map<String, Object> map = new HashMap<>();

            map.put("projectId", p.getProjectId());
            map.put("activityId", p.getActivityId());
            map.put("unit", p.getUnit());
            map.put("leader", p.getLeader());
            map.put("name", p.getName());
            map.put("info", p.getInfo());
            map.put("score", p.getScore());
            map.put("docUrl", p.getDocUrl());

            Score sc = new Score(userId, p.getProjectId());
            if ( 0 < scoreMapper.selectScoreIsExist(sc)) {
                map.put("isScored", "已评分");
            } else {
                map.put("isScored", "未评分");
            }
            if (redisMapper.hasKey(Constant.TAG_ACTIVITY + activityId.toString())) {
                map.put("tag", redisMapper.get(Constant.TAG_ACTIVITY + activityId.toString()));
            } else {
                map.put("tag", "");
            }

            lm.add(map);
        });

        return lm;
    }

    @Override
    public boolean deleteProjectsByActivityId(Integer activityId) {
        return projectMapper.deleteProjectsByActivityId(activityId);
    }
}
